<?php
namespace App\Models;

class Nc extends Base {

    public function initialize() {
        parent::initialize();
    }

    public function getSource() {
        return "nc";
    }

    private function t() {
        return 'App\Models\Nc';
    }

    /**
     * 获取NC号码
     *
     * @param string $mobile nc号码
     *
     * @return array|false
     */
    public function gets($mobile) {
        $query = $this->select('*')->from($this->t());
        $query->andWhere('mobile=:mobile:', ['mobile' => $mobile]);
        try {
            $ret = $query->getQuery()->execute();
            if($ret !== false) {
                return $ret->toArray();
            }
        } catch(\PDOException $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    /**
     * 添加NC号码
     *
     * @param array $mobiles NC号码数组
     *
     * @return int|false
     */
    public function add($mobiles) {
        $query = "REPLACE INTO `nc` VALUES ('" . implode("'),('", $mobiles) . "')";
        try {
            if($this->db()->execute($query) !== false) {
                return true;
            }
        } catch(\PDOException $ex) {
            $this->errorLog('REPLACE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    /**
     * 批量删除NC号码
     *
     * @param array $mobiles NC号码数组
     *
     * @return int|false
     */
    public function dels($mobiles) {
        $query = "DELETE FROM `nc` WHERE `mobile` IN ('" . implode("','", $mobiles) . "')";
        try {
            if($this->db()->execute($query) !== false) {
                return true;
            }
        } catch(\PDOException $ex) {
            $this->errorLog('REPLACE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    /**
     * 批量更新;
     * 先清空表;然后新增
     *
     * @param array $mobiles NC号码数组
     *
     * @return bool
     */
    public function bulkUpdate($mobiles) {
        $query = "TRUNCATE TABLE `nc`;INSERT INTO `nc` VALUES ('" . implode("'),('", $mobiles) . "');";
        try {
            if($this->db()->execute($query) !== false) {
                return true;
            }
        } catch(\PDOException $ex) {
            $this->errorLog('REPLACE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    /**
     * 删除某个NC号码
     *
     * @param string $mobile NC号码
     *
     * @return int
     */
    public function remove($mobile) {
        try {
            return $this->db()->delete($this->getSource(), sprintf("mobile='%s' LIMIT 1", $mobile));
        } catch(\PDOException $ex) {
            $this->errorLog('DELETE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }
}

